package com.idbk.chargestation.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DrawFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PaintFlagsDrawFilter;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * 动态波浪效果
 * <p>
 * 思路：先绘制正弦曲线（或者先得出正弦曲线的坐标数据），然后从左到右绘制竖线
 * </p><p>
 * 正弦函数公式：
 * y = Asin(wx+b)+h
 * 其中：
 * w为角速度 或 周期，
 * A为振幅，
 * h为纵向偏移，
 * b为初相
 * </p>
 *
 * @author lupc
 */
public class DynamicWave extends SurfaceView implements SurfaceHolder.Callback {

    public final static String TAG = DynamicWave.class.getSimpleName();

    /**
     * 波纹1颜色
     */
    private static final int WAVE_PAINT_COLOR_1 = 0xff069a05;

    /**
     * 波纹2颜色
     */
    private static final int WAVE_PAINT_COLOR_2 = 0xff078104;

    // y = Asin(wx+b)+h
    private static final float STRETCH_FACTOR_A = 14;
    private static final int OFFSET_Y = 0;

    /**
     * 正弦函数周期
     */
    private float mCycleFactorW;

    private int mTotalWidth, mTotalHeight;

    /**
     * 波浪模型 轨迹坐标
     */
    private float[] mYPositions;

    /**
     * 波浪1 数据偏移
     */
    private int mOffsetWave1 = 0;
    /**
     * 波浪2 数据偏移
     */
    private int mOffsetWave2 = 50;

    private Paint mWavePaint;
    private Paint mWavePaint2;
    private DrawFilter mDrawFilter;

    private SurfaceHolder mHolder;

    /**
     * 当前 波浪占总体的高度（百分比）
     */
    private int mPercent = 100;

    /**
     * 最大帧数 (1000 / 30)
     */
    private static final int DRAW_INTERVAL = 30;

    public DynamicWave(Context context, AttributeSet attrs) {
        super(context, attrs);

        // 初始绘制波纹的画笔
        mWavePaint = new Paint();
        // 去除画笔锯齿
        mWavePaint.setAntiAlias(true);
        // 设置风格为实线
        mWavePaint.setStyle(Style.FILL);
        // 设置画笔颜色
        mWavePaint.setColor(WAVE_PAINT_COLOR_1);

        // 初始绘制波纹的画笔
        mWavePaint2 = new Paint();
        // 去除画笔锯齿
        mWavePaint2.setAntiAlias(true);
        // 设置风格为实线
        mWavePaint2.setStyle(Style.FILL);
        // 设置画笔颜色
        mWavePaint2.setColor(WAVE_PAINT_COLOR_2);


        mDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);

        mHolder = this.getHolder();
        mHolder.addCallback(this);
    }

    /**
     * 根据高宽 初始化相关数据
     *
     * @param width  宽
     * @param height 高
     */
    private void initData(int width, int height) {
        // 记录下view的宽高
        mTotalWidth = width;
        mTotalHeight = height;
        // 用于保存原始波纹的y值
        mYPositions = new float[mTotalWidth];

        // 将周期定为view总宽度
        mCycleFactorW = (float) (2 * Math.PI / mTotalWidth);

        // 根据view总宽度得出所有对应的y值
        for (int i = 0; i < mTotalWidth; i++) {
            mYPositions[i] = (float) (STRETCH_FACTOR_A * Math.sin(mCycleFactorW * i) + OFFSET_Y);
        }
    }

    private void drawSprite(Canvas canvas) {
        //清屏
        canvas.drawColor(Color.rgb(48, 167, 20));

        //绘制
        // 从canvas层面去除绘制时锯齿
        canvas.setDrawFilter(mDrawFilter);

        //从左到右绘制竖线
        for (int i = 0; i < mTotalWidth; i++) {
            canvas.drawLine(
                    i,
                    getWave1YValue(i), //主要是得出Y值
                    i,
                    mTotalHeight,
                    mWavePaint);
        }

        for (int i = 0; i < mTotalWidth; i++) {
            canvas.drawLine(
                    i,
                    getWave2YValue(i), //主要是得出Y值
                    i,
                    mTotalHeight,
                    mWavePaint2);
        }

        //绘制 水泡
        drawBubble(canvas);

        //
        mOffsetWave1 = mOffsetWave1 + 4;
        mOffsetWave2 = mOffsetWave2 + 4;
    }

    private void drawBubble(Canvas canvas) {

    }

    /**
     * @param index
     * @return
     */
    private float getWave1YValue(int index) {
        float y = 0;

        //先求出真正的数据偏移
        int offset = (mOffsetWave1 + index) % mTotalWidth;

        //
        y = mTotalHeight - mTotalHeight * mPercent / 100f + mYPositions[offset];

        if (y < 0) {
            return 0;
        } else if (y > mTotalHeight) {
            return mTotalHeight;
        } else {
            return y;
        }
    }

    private float getWave2YValue(int index) {
        float y = 0;

        //先求出真正的数据偏移
        int offset = (mOffsetWave2 + index) % mTotalWidth;

        //
        y = mTotalHeight - mTotalHeight * mPercent / 100f + mYPositions[offset];

        if (y < 0) {
            return 0;
        } else if (y > mTotalHeight) {
            return mTotalHeight;
        } else {
            return y;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (null == mDrawThread) {
            mDrawThread = new DrawThread();
            mDrawThread.start();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        initData(width, height);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (null != mDrawThread) {
            mDrawThread.stopThread();
            mDrawThread = null;
        }
    }

    /**
     * 绘制线程
     */
    private DrawThread mDrawThread;

    /**
     * 线程驱动
     *
     * @author lupc
     */
    private class DrawThread extends Thread {

        private boolean isRunning = false;

        public DrawThread() {
            isRunning = true;
        }

        public void stopThread() {
            isRunning = false;
            boolean workIsNotFinish = true;
            while (workIsNotFinish) {
                try {
                    Log.d(TAG, "开始调用 波浪绘制线程的 join方法");
                    this.join();// 保证run方法执行完毕
                    Log.d(TAG, "结束调用 波浪绘制线程的 join方法");
                } catch (InterruptedException e) {
                    Log.e(TAG, e.getMessage(), e);
                    e.printStackTrace();
                }
                workIsNotFinish = false;
            }
            Log.d(TAG, "stop线程方法调用结束");
        }

        @Override
        public void run() {
            long deltaTime = 0;
            long tickTime = 0;
            tickTime = System.currentTimeMillis();
            while (isRunning) {
                Canvas canvas = null;
                try {
                    synchronized (mHolder) {
                        canvas = mHolder.lockCanvas();
                        if (canvas != null) {
                            //执行绘制工作
                            drawSprite(canvas);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (null != mHolder && canvas != null) {
                        mHolder.unlockCanvasAndPost(canvas);
                    }
                }

                deltaTime = System.currentTimeMillis() - tickTime;
                if (deltaTime < DRAW_INTERVAL) {
                    try {
                        Thread.sleep(DRAW_INTERVAL - deltaTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                tickTime = System.currentTimeMillis();
            }
            Log.d(TAG, "线程执行完毕");
        }

    }

    ;

    /**
     * 设置波浪高度百分比
     *
     * @param value
     */
    public void setCurrentValue(int value) {
        if (value < 0 || value > 100) {
            return;
        }
        //根据高度 计算出 波浪的高度
        mPercent = value;
    }


}